<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-20 14:35:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-11-07 05:49:20
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Edit.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { reactive, ref, unref } from 'vue'
// import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'
import { Table } from '@/components/Table'
import { useForm } from '@/hooks/web/useForm'
import File from '../../../Components/File.vue'
import { useIcon } from '@/hooks/web/useIcon'
// import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
import {
  zcInsuranceOrderSeeApi,
  zcInsuranceOrderDetailedListApi,
  sysRelFileListApi,
  sysRelFileBatchDelApi,
  sysRelFileBatchAddApi
} from '@/api/fa/insurance'
const data = ref<any>({})
import { useCache } from '@/hooks/web/useCache'
import { ucOrgListApi } from '@/api/uc/org'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const props = defineProps({
  id: {
    type: Number,
    default: null
  },
  currentRow: {
    type: Object,
    default: () => null
  },
  detailSchema: {
    type: Array,
    default: () => []
  }
})
const loading = ref({
  tree: false,
  save: false
})
// 调用查看接口获取信息
const getSee = async () => {
  if (props.id) {
    const res = await zcInsuranceOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = res.data
      if (data.value.insurance_org_id) {
        insuranceDeptList(data.value.insurance_org_id)
        if (data.value.insurance_dept_id) {
          insuranceUserList(data.value.insurance_dept_id, 'a')
        }
      }
      await methodsForm.setValues(data.value)
    }
  } else {
    data.value.state = '1'
  }
}

// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const getDetail = async () => {
  const res = await zcInsuranceOrderDetailedListApi({ insurance_order_id: props.id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value.selectData = res.data
  }
}

const getSeeFile = async () => {
  if (props.currentRow.id) {
    const res = await sysRelFileListApi({
      source_id: props.currentRow.id,
      source: 'insurance_order',
      pageNo: 1,
      pageSize: 50
    })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      res.data.forEach((element) => {
        element.url = element.file_url
      })
      fileList.value = res.data
    }
  }
}

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  // await methodsForm.setValues(data.value)
  return {
    ...formData
  }
}
const insuranceDeptTreeData = ref<any[]>([])
const insuranceUserData = ref<any[]>([])

// 选择保险组织
const insuranceonCustomer = async (value) => {
  if (value != data.value.insurance_org_id) {
    data.value.insurance_org_id = value
    insuranceDeptTreeData.value = []
    data.value.insurance_dept_id = ''
    data.value.insurance_dept_name = ''
    data.value.insurance_user_id = ''
    data.value.insurance_user_name = ''
    await insuranceDeptList(value)
  }
  await methodsForm.setValues(data.value)
}
// 保险部门列表
const insuranceDeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    insuranceDeptTreeData.value = res.data
  }
}

const insuranceUserList = async (value, a) => {
  console.log(data, '198')
  data.value.insurance_dept_id = value
  if (!a) {
    data.value.insurance_user_name = ''
    data.value.insurance_user_id = ''
  }

  insuranceUserData.value = []
  const res = await ucOrgDeptUserListApi({ org_id: data.value.insurance_org_id, dept_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    insuranceUserData.value = res.data
    await methodsForm.setValues(data.value)
  }
}

const insurancestateChangeUser = async (value) => {
  data.value.insurance_user_id = value
}
const assets_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 150
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 150
  },
  {
    field: 'earcon_code',
    label: '耳标编码',
    width: 150
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 200,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  }
])
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
const fileList = ref<UploadUserFile[]>([])
const newFileList = ref<UploadUserFile[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const selectFile = () => {
  dialogTitle.value = '选择上传文件'
  dialogVisible.value = true
  actionType.value = 'selectFile'
}

const action = async (type: string, row) => {
  switch (type) {
    case 'del':
      // 删除附件
      let delRes = await sysRelFileBatchDelApi({ ids: [row.id] })
        .catch(() => {})
        .finally(() => {})
      if (delRes) {
        await getSeeFile()
      }
      break
    default:
      console.log('未知类型')
  }
}
const selectFileRef = ref<ComponentRef<typeof File>>()

const save = async (type: string) => {
  switch (type) {
    case 'selectFile':
      const selectFile = unref(selectFileRef)
      loading.value.save = true
      newFileList.value = await selectFile?.selectData
      let res = await sysRelFileBatchAddApi({
        source: 'insurance_order',
        source_id: props.currentRow.id,
        file_ids: newFileList.value.map((element) => element.id)
      })
        .catch(() => {})
        .finally(() => {})
      if (res) {
        await getSeeFile()
      }

      loading.value.save = false
      dialogVisible.value = false
      break
    default:
      console.log('未知类型')
  }
}

const ucMyOrgList = () => {
  return ucOrgListApi({
    terminal_type: '5'
  })
}

const stateChange = async (value) => {
  data.value.insurance_type = value
}
const schema = reactive<FormSchema[]>([
  {
    field: 'insurance_org_id',
    label: '保险组织',
    component: 'DialogRefer',
    componentProps: {
      getListApi: ucMyOrgList,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'insurance_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } },
        { field: 'org_id', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.insurance_org_name,
      onChange: insuranceonCustomer
    }
  },
  {
    field: 'insurance_dept_id',
    label: '保险部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'insurance_dept_name',
      data: insuranceDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      modelName: data.value.insurance_dept_name,
      onChange: insuranceUserList
    }
  },
  {
    field: 'insurance_user_id',
    label: '负责人',
    component: 'TreeSelect',
    componentProps: {
      data: insuranceUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: insurancestateChangeUser
    }
  },
  {
    field: 'insurance_type',
    label: '保险类型',
    component: 'Select',
    componentProps: {
      options: dict.insurance_type,
      onChange: stateChange
    }
  },
  {
    field: 'number',
    component: 'Input',
    label: '承保数量'
  },
  {
    field: 'insurance_data',
    component: 'DatePicker',
    label: '投保时间',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'unitAmount',
    component: 'Input',
    label: '单位保额(元)'
  },
  {
    field: 'amount',
    component: 'Input',
    label: '保险金额(元)'
  },
  {
    field: 'rate',
    component: 'Input',
    label: '费率%'
  },
  {
    field: 'premium',
    component: 'Input',
    label: '保费(元)'
  },
  {
    field: 'years',
    component: 'Input',
    label: '投保年限'
  },
  {
    field: 'insurance_no',
    component: 'Input',
    label: '保险单号'
  },
  {
    field: 'insurance_note',
    component: 'Input',
    label: '备注'
  }
])
const file_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'file_url',
    label: '文件'
  },
  {
    field: 'file_size',
    label: '文件大小',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    table: { show: true },
    search: { show: false },
    form: { show: true },
    detail: { show: false }
  },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作'
  }
])

const {
  register: registerForm,
  methods: methodsForm
  // elFormRef
} = useForm({
  schema
})
const dblclick = async (a) => {
  const url = a.file_url // 打开的地址
  window.open(url)
}
const init = async () => {
  await getSee()
  await getDetail()
  await getSeeFile()
}
init()

defineExpose({
  data,
  getFormData
})
</script>

<template>
  <ContentWrap title="主数据">
    <Descriptions :schema="detailSchema" :data="currentRow || {}">
      <template #insurance_type="{ row }: { row: any }">
        <div>{{ getDictLabel('insurance_type', row.insurance_type) }}</div>
      </template>
      <template #state="{ row }: { row: any }">
        <div>{{ getDictLabel('insurance_order_state', row.state) }}</div>
      </template>
      <template #breed="{ row }: { row: any }">
        <div>{{ getDictLabel('breed', row.breed) }}</div>
      </template>
      <template #breed_sub="{ row }: { row: any }">
        <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
      </template>
    </Descriptions>
  </ContentWrap>
  <ContentWrap title="投保资产">
    <Table :columns="assets_columns" :data="data.selectData" :selection="false" :border="true" />
  </ContentWrap>
  <ContentWrap title="保险合同信息">
    <Form @register="registerForm" :data="data" />
  </ContentWrap>
  <ContentWrap title="上传保险合同">
    <ElButton class="mb-10px" type="primary" @click.stop="selectFile">选择文件</ElButton>
    <Table :columns="file_columns" :data="fileList" :selection="false" @row-dblclick="dblclick">
      <template #file_url="{ row }">
        <div>
          <ElImage
            v-if="row.file_type == 1 || row.mime_type == 'image/jpeg'"
            style="width: 40px; height: 40px; border-radius: 10px"
            :src="row.file_url"
          />
          <ElImage
            v-if="row.suffix_name == 'doc' || row.suffix_name == 'docx'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.doc@3x.png"
          />
          <ElImage
            v-if="row.suffix_name == 'xls' || row.suffix_name == 'xlsx'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.sheet@3x.png"
          />
          <ElImage
            v-if="row.suffix_name == 'ppt'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.slide.png"
          />
          <ElImage
            v-if="row.suffix_name == 'file'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.folder.png"
          />
          <ElImage
            v-if="row.suffix_name == 'txt'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://img1.baidu.com/it/u=4162092432,2125414077&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=300"
          />
          <span class="span" style="padding-left: 5px">{{ row.name + '.' + row.suffix_name }}</span>
        </div>
      </template>
      <template #file_size="{ row }">
        <span v-if="row.file_size">{{ row.file_size + `KB` }}</span>
      </template>
      <template #action="{ row }">
        <ElButton circle :icon="iconDel" @click="action('del', row)" title="删除行" />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <File v-if="actionType == 'selectFile'" ref="selectFileRef" :id="Number(data.pasture_org_id)" />
    <template #footer>
      <ElButton type="primary" :loading="loading.save" @click="save(actionType)"> 保存 </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
